package com.jstyle.jclife.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceConst;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.SetPersonalInfo;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.MyWheelAdapter;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.NetResultData;
import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.utils.ImageUtils;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.PermissionsUtil;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.view.BpCalibrationDialog;
import com.jstyle.jclife.view.EditTextWithDelete;
import com.jstyle.jclife.view.HeadCircleView;
import com.jstyle.jclife.view.widget.views.OnWheelChangedListener;
import com.jstyle.jclife.view.widget.views.WheelView;

import java.io.File;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 添加使用者设置信息
 */
public class UserInfoSettingActivity extends BaseActivity implements BpCalibrationDialog.CalibrationResultListener {


    @BindView(R.id.tv_set_userinfo_title)
    TextView tvSetUserinfoTitle;
    @BindView(R.id.tv_set_userinfo_tips)
    TextView tvSetUserinfoTips;
    @BindView(R.id.wheelView_setuserinfo_1)
    WheelView wheelViewSetuserinfo1;
    @BindView(R.id.et_setuserinfo_name)
    EditTextWithDelete etSetuserinfoName;
    @BindView(R.id.bt_setuserinfo_next)
    Button btSetuserinfoNext;

    List<String> weightLabelList = new ArrayList<>();
    List<String> heightLabelList = new ArrayList<>();
    List<String> birthdayLabelList = new ArrayList<>();
    List<String> yearList = new ArrayList<>();
    List<String> dayList = new ArrayList<>();
    List<String> monthList = new ArrayList<>();
    List<String> heightList = new ArrayList<>();
    List<String> weightList = new ArrayList<>();
    List<String> HighBpList = new ArrayList<>();
    List<String> LowBpList = new ArrayList<>();
    String[] titleArrays;
    String[] tipsArrays;
    @BindView(R.id.iv_icon_usersetting)
    ImageView ivIconUsersetting;
    @BindView(R.id.rb_male)
    RadioButton rbMale;
    @BindView(R.id.rb_female)
    RadioButton rbFemale;
    @BindView(R.id.rg_gender)
    RadioGroup rgGender;
    @BindView(R.id.wheelView_setuserinfo_2)
    WheelView wheelViewSetuserinfo2;
    @BindView(R.id.wheelView_setuserinfo_3)
    WheelView wheelView3;
    @BindArray(R.array.weight_labels)
    String[] weightLabels;
    @BindArray(R.array.height_labels)
    String[] heightLabels;
    @BindArray(R.array.birthday_labels)
    String[] birthdayLabels;
    public static final String userinfo_mode = "userinfo_mode";
    @BindView(R.id.bt_setuserinfo_skip)
    Button btSetuserinfoSkip;
    private String nickName;
    int age;
    String birthday;
    int gender;
    int height;
    int weight;
    int hand;
    private String name;
    public static final int mode_icon = 0;
    public static final int mode_nickname = 1;
    public static final int mode_gender = 2;
    public static final int mode_height = 3;
    public static final int mode_weight = 4;
    public static final int mode_birthday = 5;
    public static final int mode_BP = 6;
    private MyWheelAdapter wheelAdapter;
    private MyWheelAdapter wheelAdapter2;
    private MyWheelAdapter wheelAdapter3;
    private int currentItem;
    private AlertDialog iconDialog;
    private Uri caremaUri;
    private HeadCircleView circleView;
    private Bitmap bm;
    Uri iconUri;
    private UserInfo userInfo;
    private int monthItem;
    private int dayItem;
    private int yearItem;
    private int mode;
    int weightLabel;
    int heightLabel;
    private boolean isFirst;
    private int weightUnit;
    private NumberFormat nf;
    private int heightUnit;
    private int intFloot;
    private int intInch;
    private BpCalibrationDialog bpCalibrationDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info_setting);
        ButterKnife.bind(this);
        initData();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void requestPermissions() {
        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                setHeadIcon();
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
    }

    private void initData() {
        nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(0);

        nf.setGroupingUsed(false);
        //  isFirst = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_Is_First, true);
        mode = getIntent().getIntExtra(userinfo_mode, -1);
        if (mode != -1) {
            count = mode;
            btSetuserinfoNext.setText(getString(R.string.Confirm));
            btSetuserinfoSkip.setVisibility(View.GONE);
        }
        name = "";
        tipsArrays = getResources().getStringArray(R.array.set_userinfo_tips);
        titleArrays = getResources().getStringArray(R.array.set_userinfo_title);
        weightLabelList.addAll(Arrays.asList(weightLabels));
        birthdayLabelList.addAll(Arrays.asList(birthdayLabels));


        Calendar calendar = Calendar.getInstance();
        yearList = getListData(1920, calendar.get(Calendar.YEAR) + 1);
        monthList = getListData(1, 13);
        String account = NetWorkUtil.getUserId();
        userInfo = UserInfoDaoManager.getUserByUid(account);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(account);
            UserInfoDaoManager.insertUser(userInfo);
        }
        age = userInfo.getAge();
        gender = userInfo.getGender();
        hand = userInfo.getHand();
        name = userInfo.getName();
        height = userInfo.getHeight();
        weight = userInfo.getWeight();
        birthday = userInfo.getBirthday();
        heightLabel = userInfo.getHeightLabel();
        weightLabel = userInfo.getWeightLabel();
        initHeightList();
        initWeightList();
        HighBpList = getListData(0, 256);
        LowBpList = getListData(0, 256);
        String[] date = birthday.split("-");
        yearItem = yearList.indexOf(date[0]);
        monthItem = monthList.indexOf(date[1]);
        int dayMax = getMaxDayOfMonth(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1);
        dayList = getListData(1, dayMax + 1);
        dayItem = dayList.indexOf(date[2]);
        if (!TextUtils.isEmpty(name)) etSetuserinfoName.setText(name);
        //setHeadIcon();
    }

    private void initHeightList() {
        heightUnit = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_UNIT_HEIGHT, 0);
        heightList = heightUnit == 0 ? getListData(30, 242) : getListData(1, 8);
        if (heightUnit == 1) {
            heightLabelList = getListData(0, 12);
            float foot = height / 100.0f / 0.3048f;
            intFloot = (int) foot;
            float inch = (height / 100.0f / 0.3048f - intFloot) * 12;
            BigDecimal bigDecimal = new BigDecimal(inch);
            BigDecimal bigDecimal2 = bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP);
            intInch = bigDecimal2.intValue();
        }
    }

    private void initWeightList() {
        weightUnit = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_UNIT_WEIGHT, 0);

        weightList = weightUnit == 0 ? getListData(5, 256) : getListData(10, 563);

    }

    private List<String> getListData(int start, int end) {
        List<String> list = new ArrayList<>();
        for (int i = start; i < end; i++) {
            list.add(String.format("%02d", i));
        }
        return list;
    }


    private void initView() {
        // ScreenUtils.setStatusBarColor(llTitle, getResources().getColor(R.color.colorPrimary));

        wheelAdapter = new MyWheelAdapter(this, yearList, 0, 24, 14);
        wheelViewSetuserinfo1.setViewAdapter(wheelAdapter);

        if (!TextUtils.isEmpty(name)) etSetuserinfoName.setText(name);

        rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_female:
                        if (count == mode_gender) {
                            gender = 1;
                        } else {
                            hand = 1;
                        }
                        break;
                    case R.id.rb_male:
                        if (count == mode_gender) {
                            gender = 0;
                        } else {
                            hand = 0;
                        }
                        break;
                }
            }
        });
        changeUserInfo();

//        datePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
//        setDatePickerDividerColor(datePicker);
    }

    /**
     * 设置时间选择器的分割线颜色
     *
     * @param datePicker
     */

    int count = 0;

    @OnClick({R.id.bt_setuserinfo_skip, R.id.bt_setuserinfo_next, R.id.iv_icon_usersetting})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_setuserinfo_skip:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_Is_First, false);
                finish();
                break;
            case R.id.iv_icon_usersetting:
                showChangeIconDialog();
                break;
            case R.id.bt_setuserinfo_next:
                if (mode != -1) {
                    saveUserInfo();
                } else {
                    if (count == 5) {
                        saveUserInfo();
                    }
                    if (count == 6) {
                        showBpCalibrationDialog();
                        updateValue();
//                        SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_BPCalibration_High,Integer.valueOf(wheelAdapter.getCurrentItemText()));
//                        SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_BPCalibration_Low,Integer.valueOf(wheelAdapter2.getCurrentItemText()));
//                        Intent intent = new Intent(this, MainActivity.class);
//                        startActivity(intent);
//                        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_Is_First, false);
//                        saveUserInfo();
                        return;
                    }
                    nickName = etSetuserinfoName.getText().toString().trim();
                    if (count == mode_nickname && TextUtils.isEmpty(nickName)) {
                        showToast(getString(R.string.fill_all_info));
                        return;
                    }
                    count++;
                    changeUserInfo();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        switch (requestCode) {
            case ImageUtils.CROP_IMAGE:
                setHeadIcon();
                updateIcon();
                break;
            case ImageUtils.GET_IMAGE_BY_CAMERA:
                ImageUtils.cropImage(this, ivIconUsersetting.getWidth() * 2,
                        ivIconUsersetting.getHeight() * 2, caremaUri, iconUri);
                break;
            case ImageUtils.GET_IMAGE_FROM_PHONE:
                ImageUtils
                        .cropImage(this, ivIconUsersetting.getWidth() * 2,
                                ivIconUsersetting.getHeight() * 2, data.getData(),
                                iconUri);
                break;
            default:
                break;
        }
    }

    private void setHeadIcon() {
        // Log.i(TAG, "setHeadIcon: " + getFilesDir());
        iconUri = ImageUtils.getIconUri(this, userInfo.getUserId());
        Log.i(TAG, "setHeadIcon: " + iconUri);
        Bitmap bmHead = ImageUtils.findHeadBitmap(this, iconUri);
        bm = bmHead == null ? BitmapFactory.decodeResource(getResources(),
                R.drawable.user_icon) : bmHead;
        circleView = new HeadCircleView(bm);
        ivIconUsersetting.setImageDrawable(circleView);
    }

    private void uploadUserInfo(String token) {
        if (TextUtils.isEmpty(token)) {
            finish();
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put(NetWorkConast.KEY_birthday, birthday + "");
        map.put(NetWorkConast.KEY_uid, token);
        map.put(NetWorkConast.KEY_nickName, TextUtils.isEmpty(nickName) ? "" : nickName);
        map.put(NetWorkConast.KEY_weight, weight + "");
        map.put(NetWorkConast.KEY_stature, height + "");
        map.put(NetWorkConast.KEY_gender, gender == 0 ? "male" : "female");
        saveJstyleInfo(map);
    }

    //    private void saveFomoInfo(  Map<String, String> map ){
//        NetWorkUtil.getInstance()
//                .getJstyleApi().saveUserInfo(map).compose(SchedulersTransformer.<NetResultData<String>>applySchedulers()).subscribe(new Observer<NetResultData<String>>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(NetResultData<String> stringNetResultData) {
//                finish();
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                Log.i(TAG, "onError: "+e.getMessage());
//                finish();
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
//    }
    private void saveJstyleInfo(Map<String, String> map) {
        if (count != 6) finish();
        NetWorkUtil.getInstance()
                .getJstyleApi().saveUserInfo(map).compose(SchedulersTransformer.<NetResultData<String>>applySchedulers()).subscribe(new Observer<NetResultData<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetResultData<String> stringNetResultData) {


            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
                finish();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private static final String TAG = "UserInfoSettingActivity";


    private void saveUserInfo() {
        nickName = etSetuserinfoName.getText().toString().trim();
        switch (count) {
            case mode_birthday:
                String year = yearList.get(wheelAdapter.getCurrentItem());
                String month = monthList.get(wheelAdapter2.getCurrentItem());
                String day = dayList.get(wheelAdapter3.getCurrentItem());
                birthday = year + "-" + month + "-" + day;
                break;
            case mode_height:
                int heightItem = wheelViewSetuserinfo1.getCurrentItem();
                String heightS = heightList.get(heightItem);
                if (heightUnit == 1) {
                    String heightInchString = heightLabelList.get(heightLabel);
                    float heightFt = Integer.valueOf(heightS) * 30.48f;
                    float heightInch = Integer.valueOf(heightInchString) * 2.54f;
                    height = (int) (heightFt + heightInch);
                    Log.i(TAG, "onChanged: " + height);
                } else {
                    height = Integer.valueOf(heightS);
                }
                heightLabel = wheelViewSetuserinfo2.getCurrentItem();
                break;
            case mode_weight:
                int weightItem = wheelViewSetuserinfo1.getCurrentItem();
                weightLabel = wheelViewSetuserinfo2.getCurrentItem();
                String weightS = weightList.get(weightItem);
                weight = Integer.valueOf(weightS);
                if (weightUnit == 1) {
                    BigDecimal bigDecimaWeight = new BigDecimal(weight * 0.454f);
                    BigDecimal bigDecimal2 = bigDecimaWeight.setScale(0, BigDecimal.ROUND_HALF_UP);
                    weight = bigDecimal2.intValue();
//                    String value = nf.format(weight * 0.454f);
//                    weight = Integer.valueOf(value);
                }
                break;

        }
        userInfo.setBirthday(birthday);
        userInfo.setGender(gender);
        userInfo.setHeight(height);
        userInfo.setWeight(weight);
        userInfo.setName(nickName);
        userInfo.setHand(hand);
        userInfo.setHeightLabel(heightLabel);
        userInfo.setWeightLabel(weightLabel);
        updateDeviceUserInfo();
        UserInfoDaoManager.updateUser(userInfo);
        uploadUserInfo(String.valueOf(userInfo.getUserId()));
    }

    private void updateDeviceUserInfo() {
        SetPersonalInfo setPersonalInfo = new SetPersonalInfo();
        Calendar calendar = Calendar.getInstance();
        int nowYear = calendar.get(Calendar.YEAR);
        int userYear = Integer.parseInt(userInfo.getBirthday().split("-")[0]);
        float height = userInfo.getHeight();
        float weight = userInfo.getWeight();
        setPersonalInfo.setAge(nowYear - userYear);
        setPersonalInfo.setHeight((int) height);
        setPersonalInfo.setWeight((int) weight);
        setPersonalInfo.setSex(userInfo.getGender() == 0 ? 1 : 0);
        sendData(SendCmdState.SET_PERSONAL_INFO, setPersonalInfo);
    }

    private void changeUserInfo() {

        showVisibility();
        switch (count) {
            case mode_icon:
                showIcon();
                break;
            case mode_nickname:
                showNickName();
                break;
            case mode_gender:
                showGender();
                break;
            case mode_height:
                showHeight();
                if (mode == -1) {
                    showUnitDialog();
                }
                break;
            case mode_weight:

                if (mode == -1) {
                    showUnitDialog();
                } else {
                    showWeight();
                }
                break;
            case mode_birthday:
                showBirthday();
                break;
            case mode_BP:
                showBP();
                break;
        }
        changeTv();
        requestPermissions();

    }

    private void changeTv() {
        tvSetUserinfoTitle.setText(titleArrays[count]);
    }

    private void showVisibility() {

        etSetuserinfoName.setVisibility(count == mode_nickname ? View.VISIBLE : View.GONE);
        ivIconUsersetting.setVisibility(count == mode_icon ? View.VISIBLE : View.GONE);
        if (count == mode_gender) {
            rgGender.setVisibility(View.VISIBLE);
        } else {
            rgGender.setVisibility(View.GONE);
        }
        if (count == mode_BP || count == mode_birthday || count == mode_height || count == mode_weight) {
            wheelViewSetuserinfo1.setVisibility(View.VISIBLE);

        } else {
            wheelViewSetuserinfo1.setVisibility(View.GONE);
            wheelViewSetuserinfo2.setVisibility(View.GONE);
        }
        wheelView3.setVisibility(count == mode_birthday ? View.VISIBLE : View.GONE);
        if (count == mode_BP || count == mode_birthday) {
            wheelViewSetuserinfo2.setVisibility(View.VISIBLE);
        } else {
            wheelViewSetuserinfo2.setVisibility(View.GONE);
        }
//       if(count==mode_birthday)viewstubDate.inflate();


    }

    private void showIcon() {
        tvSetUserinfoTips.setText(tipsArrays[0]);

    }

    private void showNickName() {
        tvSetUserinfoTips.setText(tipsArrays[1]);

    }

    private void showGender() {
        rgGender.check(gender == 0 ? R.id.rb_male : R.id.rb_female);
        tvSetUserinfoTips.setText(tipsArrays[2]);
    }

    OnWheelChangedListener heightLabelListener;
    OnWheelChangedListener heightListener;

    private void showHeight() {

        heightLabelListener = new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                heightLabel = wheelViewSetuserinfo2.getCurrentItem();
            }
        };
        heightListener = new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                if (count != mode_height) return;
                int heightItem = wheelViewSetuserinfo1.getCurrentItem();
                String heightS = heightList.get(heightItem);
                if (heightUnit == 1) {
                    String heightInchString = heightLabelList.get(heightLabel);
                    float heightFt = Integer.valueOf(heightS) * 30.48f;
                    float heightInch = Integer.valueOf(heightInchString) * 2.54f;
                    height = (int) (heightFt + heightInch);
                    Log.i(TAG, "onChanged: " + heightFt + " " + heightInch);
                } else {
                    height = Integer.valueOf(heightS);
                }

            }
        };
        tvSetUserinfoTips.setText(tipsArrays[3]);
        wheelAdapter = new MyWheelAdapter(this, heightList, 0, 24, 14);
        wheelAdapter2 = new MyWheelAdapter(this, heightLabelList, 0, 24, 14);
        currentItem = heightList.indexOf(height + "");
        if (heightUnit == 1) {
            Log.i(TAG, "showHeight: " + intFloot + " " + intInch);
            currentItem = heightList.indexOf(String.format("%02d", intFloot));
            heightLabel = heightLabelList.indexOf(String.format("%02d", intInch));
            wheelViewSetuserinfo1.setLabel("ft");
            wheelViewSetuserinfo2.setVisibility(View.VISIBLE);
            wheelViewSetuserinfo2.setLabel("in");
        } else {
            wheelViewSetuserinfo1.setLabel("cm");
        }
        wheelViewSetuserinfo1.setViewAdapter(wheelAdapter);
        wheelViewSetuserinfo1.setCurrentItem(currentItem);
        wheelViewSetuserinfo2.setViewAdapter(wheelAdapter2);
        wheelViewSetuserinfo2.setCurrentItem(heightLabel);
        wheelViewSetuserinfo2.addChangingListener(heightLabelListener);
        wheelViewSetuserinfo1.addChangingListener(heightListener);

    }

    private void showWeight() {
        if (heightListener != null) wheelViewSetuserinfo1.removeChangingListener(heightListener);
        if (heightLabelListener != null)
            wheelViewSetuserinfo2.removeChangingListener(heightLabelListener);
        tvSetUserinfoTips.setText(tipsArrays[4]);
        wheelAdapter = new MyWheelAdapter(this, weightList, 0, 24, 14);
        wheelAdapter2 = new MyWheelAdapter(this, weightLabelList, 0, 16, 14);
        if (weightUnit == 1) {
            BigDecimal bigDecimaWeight = new BigDecimal(weight / 0.454f);
            BigDecimal bigDecimal2 = bigDecimaWeight.setScale(0, BigDecimal.ROUND_HALF_UP);
            weight = bigDecimal2.intValue();
            wheelViewSetuserinfo1.setLabel("lb");
        } else {
            wheelViewSetuserinfo1.setLabel("kg");
        }
        currentItem = weightList.indexOf(weight + "");
        wheelViewSetuserinfo1.setViewAdapter(wheelAdapter);
        wheelViewSetuserinfo1.setCurrentItem(currentItem);
        wheelViewSetuserinfo2.setViewAdapter(wheelAdapter2);

        //  Log.i(TAG, "showWeight: "+weightLabelList.indexOf(weightLabel+""));
        wheelViewSetuserinfo2.setCurrentItem(weightLabel);
    }

    private OnWheelChangedListener wheelChangedListenerYear;
    private OnWheelChangedListener wheelChangedListenerMonth;
    private OnWheelChangedListener wheelChangedListenerDay;

    private void showBirthday() {
        tvSetUserinfoTips.setText(tipsArrays[5]);
        if (mode == -1) {
            int heightItem = wheelViewSetuserinfo1.getCurrentItem();
            String heightS = weightList.get(heightItem);
            weight = Integer.valueOf(heightS);
            weightLabel = wheelViewSetuserinfo2.getCurrentItem();
        }

        wheelAdapter = new MyWheelAdapter(this, yearList, yearItem, 24, 14);
        wheelViewSetuserinfo1.setLabel(getString(R.string.birthday_year));
        wheelAdapter2 = new MyWheelAdapter(this, monthList, monthItem, 24, 14);
        wheelViewSetuserinfo2.setLabel(getString(R.string.birthday_month));
        currentItem = yearList.indexOf(age + "");
        wheelViewSetuserinfo1.setViewAdapter(wheelAdapter);
        wheelViewSetuserinfo2.setViewAdapter(wheelAdapter2);
        wheelAdapter3 = new MyWheelAdapter(this, dayList, dayItem, 24, 14);
        wheelView3.setLabel(getString(R.string.birthday_day));
        wheelView3.setViewAdapter(wheelAdapter3);
        wheelViewSetuserinfo1.setCurrentItem(currentItem);
        wheelChangedListenerYear = new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                changeDayOfMonth();
            }
        };
        wheelViewSetuserinfo1.addChangingListener(wheelChangedListenerYear);
        wheelChangedListenerMonth = new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                changeDayOfMonth();
            }
        };
        wheelViewSetuserinfo2.addChangingListener(wheelChangedListenerMonth);
    }

    private int getMaxDayOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    private void changeDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        int yearNow = calendar.get(Calendar.YEAR);
        int monthNow = calendar.get(Calendar.MONTH);
        int dayNow = calendar.get(Calendar.DAY_OF_MONTH);
        String year = yearList.get(wheelAdapter.getCurrentItem());

        monthList = yearNow != Integer.valueOf(year) ? getListData(1, 13) : getListData(1, monthNow + 2);
        int monthItem = wheelAdapter2.getCurrentItem();
        if (monthItem >= monthList.size()) monthItem = monthList.size() - 1;
        wheelAdapter2 = new MyWheelAdapter(this, monthList, monthItem, 24, 14);
        wheelViewSetuserinfo2.setLabel(getString(R.string.birthday_month));
        wheelViewSetuserinfo2.setViewAdapter(wheelAdapter2);

        String month = monthList.get(wheelAdapter2.getCurrentItem());

        int day = getMaxDayOfMonth(Integer.parseInt(year), Integer.parseInt(month) - 1);
        if (yearNow == Integer.parseInt(year) && Integer.parseInt(month) - 1 == monthNow) {
            day = dayNow;
        }
        dayList = getListData(1, day + 1);
        currentItem = wheelAdapter3.getCurrentItem();
        if (currentItem >= dayList.size()) currentItem = dayList.size() - 1;
        wheelAdapter3 = new MyWheelAdapter(this, dayList, currentItem, 24, 14);
        wheelView3.setLabel(getString(R.string.birthday_day));
        wheelView3.setViewAdapter(wheelAdapter3);
    }

    private void showBP() {
        if (heightListener != null) wheelViewSetuserinfo1.removeChangingListener(heightListener);
        if (heightLabelListener != null)
            wheelViewSetuserinfo2.removeChangingListener(heightLabelListener);
        if (wheelChangedListenerMonth != null)
            wheelViewSetuserinfo2.removeChangingListener(wheelChangedListenerMonth);
        if (wheelChangedListenerYear != null)
            wheelViewSetuserinfo1.removeChangingListener(wheelChangedListenerYear);
        tvSetUserinfoTips.setText(tipsArrays[6]);
        wheelAdapter = new MyWheelAdapter(this, HighBpList, 0, 24, 14);
        wheelAdapter2 = new MyWheelAdapter(this, LowBpList, 0, 24, 14);
        wheelViewSetuserinfo1.setLabel("SP");
        wheelViewSetuserinfo2.setLabel("DP");
        wheelViewSetuserinfo1.setViewAdapter(wheelAdapter);
        wheelViewSetuserinfo1.setCurrentItem(120);
        wheelViewSetuserinfo2.setViewAdapter(wheelAdapter2);
        wheelViewSetuserinfo2.setCurrentItem(80);
    }

    private void showChangeIconDialog() {
        if (iconDialog == null) {
            iconDialog = new AlertDialog.Builder(this, R.style.appalertdialog).setItems(R.array.change_icon, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 1) {
                        requestCameraAndStoragePermissions(PositionCamera);
                    } else {
                        requestCameraAndStoragePermissions(PositionPicture);

                    }
                }
            }).setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).create();
        }
        iconDialog.show();
        ScreenUtils.setDialogButtonTextColor(iconDialog);
    }

    AlertDialog unitDialog;

    private void showUnitDialog() {
        String title = getString(R.string.Unit_Selection_title);
        String message = count == mode_height ? getString(R.string.height_unit_text) : getString(R.string.weight_unit_text);
        String rightTips = count == mode_height ? "ft,in" : "lb";
        String leftTips = count == mode_height ? "cm" : "kg";
        unitDialog = new AlertDialog.Builder(this, R.style.appalertdialog)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(leftTips, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (count == mode_height) {
                            SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_UNIT_HEIGHT, 0);
                            initHeightList();
                            showVisibility();
                            showHeight();
                        } else if (count == mode_weight) {
                            SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_UNIT_WEIGHT, 0);
                            initWeightList();
                            showVisibility();
                            showWeight();
                        }
                    }
                })
                .setNegativeButton(rightTips, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (count == mode_height) {
                            SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_UNIT_HEIGHT, 1);
                            initHeightList();
                            showVisibility();
                            showHeight();
                        } else if (count == mode_weight) {
                            SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_UNIT_WEIGHT, 1);
                            initWeightList();
                            showVisibility();
                            showWeight();
                        }
                    }
                })
                .setCancelable(false)
                .create();

        unitDialog.show();

    }

    private void updateIcon() {
        String uid = userInfo.getUserId();
        File file = ImageUtils.getIconPath(uid);
        if (file == null || !file.exists()) return;
        Map<String, RequestBody> maps = new HashMap<>();
        RequestBody tokenBody = RequestBody.create(MediaType.parse("text/plain"), uid);
        //   RequestBody appNameBody = RequestBody.create(MediaType.parse("multipart/form-data"), "uid");
        maps.put(NetWorkConast.KEY_uid, tokenBody);
        // maps.put(NetWorkConast.KEY_AppName, appNameBody);
        // maps.put(NetWorkConast.KEY_AppName, appNameBody);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part muPart = MultipartBody.Part.createFormData("img", file.getName() + ".png", requestBody);
        NetWorkUtil.getInstance().getJstyleApi().updateIcon(muPart, maps).map(new Function<NetResultData<String>, Object>() {
            @Override
            public Object apply(NetResultData<String> netResultData) throws Exception {
                int msgCode = netResultData.getMsgCode();
                Log.i(TAG, "apply: " + msgCode);
                if (msgCode == NetResultData.Success_Code) {
                    String url = netResultData.getData();
                    //shareTools.ShareLinkedin(url);
                }
                return new Object();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void requestCameraAndStoragePermissions(final int iconPosition) {
        PermissionsUtil.requestPermissions(this,
                new PermissionsUtil.PermissionListener() {
                    @Override
                    public void granted(String name) {
                        if (iconPosition == PositionCamera) {
                            caremaUri = ImageUtils.createImagePathUri(UserInfoSettingActivity.this);
                            ImageUtils.openCameraImage(UserInfoSettingActivity.this, caremaUri);
                        } else if (iconPosition == PositionPicture) {
                            ImageUtils.openLocalImage(UserInfoSettingActivity.this);
                        }
                    }

                    @Override
                    public void NeverAskAgain() {

                    }

                    @Override
                    public void disallow(String name) {

                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
    }

    int PositionCamera = 0;
    int PositionPicture = 1;

    private void updateValue() {
        int highValue = Integer.valueOf(wheelAdapter.getCurrentItemText());
        int lowValue = Integer.valueOf(wheelAdapter2.getCurrentItemText());
        String account = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(account);
            UserInfoDaoManager.insertUser(userInfo);
        }
        String birthday = userInfo.getBirthday();
        int userYear = Integer.parseInt(birthday.split("-")[0]);
        Calendar calendar = Calendar.getInstance();
        int age = calendar.get(Calendar.YEAR) - userYear;
        int gender = userInfo.getGender();
        byte[] value = new byte[16];
        value[0] = DeviceConst.CMD_Enable_ECGPPG;
        value[1] = (byte) 4;
        value[2] = 1;
        value[3] = (byte) (gender == 0 ? 1 : 0);
        value[4] = (byte) age;
        value[5] = (byte) userInfo.getHeight();
        value[6] = (byte) userInfo.getWeight();
        value[7] = (byte) highValue;
        value[8] = (byte) lowValue;
        value[9] = 70;
        writeData(value);
    }

    private void showBpCalibrationDialog() {
        bpCalibrationDialog = new BpCalibrationDialog(this, R.style.jstyleDialog_style);
        bpCalibrationDialog.setCalibrationListener(this);
        bpCalibrationDialog.show();
    }

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState) {
            case ResultEcg:
                Integer result = Integer.valueOf(maps.get(DeviceKey.ECGPPGResult));
                Log.i(TAG, "dataCallback: "+result);
                String info = "";
                if (result==1||result == 255 || result == 12 || result == 11) return;
                if (result == 2) {
                    info = "超时";
                } else if (result == 13) {
                    info = "校准完成";
                } else if (result == 14) {
                    info = "校准失败";
                }
                if (bpCalibrationDialog != null) bpCalibrationDialog.setBpCalibrationFinish(result);
                break;
        }
    }

    @Override
    public void onCalibrationSuccess() {
        SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_BPCalibration_High, Integer.valueOf(wheelAdapter.getCurrentItemText()));
        SharedPreferenceUtils.setSpInteger(SharedPreferenceUtils.KEY_BPCalibration_Low, Integer.valueOf(wheelAdapter2.getCurrentItemText()));
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_Is_First, false);
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onCalibrationFailed() {

    }
}
